<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <!-- <SearchForm
        :formConfig="filterItem"
        :formData="{}"
        @search="queryPageList"
      ></SearchForm>-->
      <div class="search-form">
        <div class="select-box-content">
          <div class="select-box-content-name">设备名称：</div>
          <el-input
            v-model="equipmentName"
            placeholder="请输入设备名称"
            clearable
            @change="queryPageList()"
          />
        </div>
        <div class="operationBtn">
          <div class="screenBtn">
            <div class="btn" @click="changeSelect()">
              <i
                :class="activeName === '' ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"
                class="arrow-down"
              ></i>
            </div>
          </div>
        </div>
        <el-collapse v-model="activeName" accordion @change="handleChange">
          <el-collapse-item name="1">
            <div class="select-box-content">
              <div class="select-box-content-name">设备型号：</div>
              <div
                class="select-box-content-all"
                @click="cancelSelect('model')"
              >全部</div>
              <div
                v-for="(item, index) in equModelArr"
                :key="index"
                class="select-box-content-list"
                :style="{
                  color:
                    equModelCode === item.equModelCode ? '#54DEE2' : '#C1CFD2',
                  fontWeight: equModelCode === item.equModelCode ? '600' : '400'
                }"
                @click="selectEquModelCode(item)"
              >{{ item.modelName }}</div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </template>
    <!-- <template v-slot:typenodeslot>
      <SelectButton @topitemtype="topitemtype" />
    </template>-->

    <template slot="btnsBar">
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :has-del="false"
        :page-no="138"
        @add="add"
        @del="del"
      />
    </template>

    <template slot="content">
      <div class="content-container">
        <div class="left">
          选择设备类型
          <typeTree
            class="tree-content"
            @topitemtype="topitemtype"
            @selectEquModelCode="selectEquModelCode"
          ></typeTree>
        </div>
        <e-table
          class="right"
          rowKey="equipmentCode"

          ref="tableData"
          :table-data="tableData"
          :table-columns="tableLabel"
          :page="currentPage"
          :size="pageSize"
          :total="totalSize"
          :loading="loading"
          :table-option="tableOption"
          @sizeChange="changePageSize"
          @pageChange="changeCurrentPage"
          @handleSelectionChange="handleSelectionChange"
          :table-column-sum="topitemtypeId"
          @tableUpdatePlus="mixTableUpdatePlus"
        >
          <template
            v-if="scoped.row.equipmentCode"
            slot="sellByDate"
            slot-scope="scoped"
          >
            <div v-if="scoped.row.sellByDate">{{ scoped.row.sellByDate }}月</div>
          </template>
          <template
            v-if="scoped.row.equipmentCode"
            slot="status"
            slot-scope="scoped"
          >
            <div
              v-if="scoped.row&&(scoped.row.status === '废弃')"
              :class="{
                'start-info-btn': scoped.row.status === '启用',
                'stop-info-btn': scoped.row.status === '禁用'
              }"
            >{{ scoped.row.status }}</div>
            <el-switch
              style="margin-left:10px"
              v-else-if="((scoped.row.status === '启用' && judgePermission(138, 'stop'))||(scoped.row.status === '禁用' && judgePermission(138, 'start')))"
              v-model="scoped.row.operate_status"
              active-color="#64D9D6"
              inactive-color="#9E9E9E"
              active-value="启用"
              inactive-value="禁用"
              @change="changeStatus(scoped.row)"
            ></el-switch>
            <div v-else>{{ "未获取设备状态" }}</div>
          </template>
          <template
            slot="operate"
            slot-scope="scope"
            v-if="scope.row.equipmentCode"
          >
            <!-- <el-switch
              style="margin-left:10px"
              v-if="((scope.row.status === '启用' && judgePermission(138, 'stop'))||(scope.row.status === '禁用' && judgePermission(138, 'start')))"
              v-model="scope.row.operate_status"
              active-color="#64D9D6"
              inactive-color="#9E9E9E"
              active-value="启用"
              inactive-value="禁用"
              @change="changeStatus(scope.row)"
            ></el-switch> -->
            <!-- showCompleteInfo -->
            <!-- <span
              v-if="judgePermission(138, 'info')"
              class="table-btns-box"
              @click="showCompleteInfo(scope.row)"
            >
              <i class="el-icon-circle-check"></i>
              <span>设备详情</span>
            </span> -->
            <span
              v-if="judgePermission(138, 'edit')"
              class="table-btns-box"
              @click="completeInfo(scope.row)"
            >
              <i class="el-icon-edit-outline"></i>
              <span>
                <!-- 完善设备信息 -->
                编辑设备信息
              </span>
            </span>
          </template>
        </e-table>
      </div>
    </template>
    <template slot="dialog">
      <AddEditDialog
        ref="addEditDialog"
        :now-chance-stau="nowChanceStau"
        :equ-model-arr="equModelArr"
        :title-text="titleText"
        :edit-object="editObject"
        :show.sync="showAddEditDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
      <CompleteInfoDialog
        ref="CompleteInfoDialog"
        :now-chance-stau="nowChanceStau"
        :equ-model-arr="equModelArr"
        :edit-object="editObject"
        :show.sync="showCompleteInfoDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
      <QuipmentDetailDialog
        ref="QuipmentDetailDialog"
        :now-chance-stau="nowChanceStau"
        :equ-model-arr="equModelArr"
        :edit-object="editObject"
        :show.sync="showQuipmentDetailDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar/index.vue";
import SelectButton from "@/components/equipTypeSelectButton/typeSelectParentButton.vue";
import equipStandingBookApi from "@/api/equip-manage/equip-standing-book";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import { mymixin } from "@/utils/mixin";
import AddEditDialog from "./components/add-edit-dialog.vue";
import CompleteInfoDialog from "./components/complete-info-dialog.vue";
import equipModelApi from "@/api/equip-manage/equip-model";
import equipTypeApi from "@/api/equip-manage/equip-type/index";
import { mapGetters } from "vuex";
import typeTree from "./components/type-tree";
import QuipmentDetailDialog from "./components/equipment-detail-dialog";
import {
  formItems,
  tableLabel,
  tableOption,
  dialogFormItems,
  filterItem,
  enumList,
} from "./viewConfig";
export default {
  name: "EquipStandingBook",
  components: {
    ActionBar,
    SelectButton,
    BaseMainSlot,
    AddEditDialog,
    CompleteInfoDialog,
    typeTree,
    QuipmentDetailDialog,
  },
  mixins: [mymixin],
  data() {
    return {
      treerule: {
        children: "childList",
        label: "modelName",
      },
      //  搜索条件:设备名称
      equipmentName: "",
      //  搜索条件:设备型号
      modelName: "",
      //  搜索条件:设备类型
      equipmentTypeCode: "",
      // 设备类型数组
      equipmentTypeList: [],
      defaultProps: {
        children: "childList",
        value: "equipmentTypeCode",
        label: "equipmentTypeName",
        emitPath: false,
        checkStrictly: true,
      },
      //  搜索条件:查询条件
      equModelCode: "",
      // 设备型号数组
      equModelArr: [],
      // 删除数组
      checkedIdList: [],
      // 当前的农机设备还是物联设备
      topitemtypeId: "",
      showAddEditDialog: false,
      showCompleteInfoDialog: false,
      showQuipmentDetailDialog: false,
      //顶部设备分类
      topitemSelectList: [],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),

    // 筛选项（展开）
    formItems() {
      return formItems;
    },
    // 筛选项（收起）
    filterItem() {
      return filterItem;
    },
    // 弹窗表单
    dialogFormItems() {
      return dialogFormItems;
    },
    // 表单事件
    tableOption() {
      return tableOption;
    },
    // 表单展示项
    tableLabel() {
      return tableLabel;
    },
    // 枚举项
    enumList() {
      return enumList;
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    //状态变更,点击的时候，list里的operate_status状态已经改变，需要通过status改变成之前的状态
    changeStatus(data) {
      this.tableData.forEach((item) => {
        if (item.equipmentCode === data.equipmentCode) {
          item.operate_status = item.status;
          console.log("start11", item);
          return;
        }
      });
      if (data.status === "禁用") {
        this.start(data);
      } else if (data.status === "启用") {
        this.stop(data);
      }
    },
    // 展开筛选框
    handleChange(val) {
      this.activeName = val;
    },
    // 关闭选择框
    changeCascader() {
      this.$refs.cascader.dropDownVisible = false;
      console.log(this.equipmentTypeCode);
      if (this.equipmentTypeCode) {
        this.queryEquipModel(this.equipmentTypeCode);
      }
      this.queryPageList();
    },
    // 清空选项
    cancelSelect(data) {
      if (data === "model") {
        this.equModelCode = "";
      }
      this.queryPageList();
    },
    // 选择
    selectEquModelCode(item) {
      console.log("selectEquModelCode ", item);
      if (item.topitemtypeId) this.topitemtypeId = item.topitemtypeId;
      if (this.equModelCode === item.equModelCode) {
        this.equModelCode = "";
      } else {
        this.equModelCode = item.equModelCode;
      }
      this.queryPageList();
    },
    // 设备模型
    queryEquipModel(date) {
      this.loading = false;
      // 获取数据
      equipModelApi.queryAllEquModel(date).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || [];
          this.equModelArr = [];

          console.log("queryAllEquModel start", this.tableLabel);
          for (var i in data) {
            this.equModelArr.push({
              modelName: data[i],
              equModelCode: i,
            });
          }
          let index = 0;
          let item = null;
          this.tableLabel.forEach((el, i) => {
            if (el.param === "modelName") {
              index = i;
              item = el;
              item.typeObj.list = this.equModelArr;
              console.log("queryAllEquModel item ", item);
            }
          });
          if (item) this.$set(this.tableLabel, index, item);
          console.log("queryAllEquModel", this.tableLabel);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 转换设备型号编号到名字
    changeModelNameByEquModelCode(v) {
      var index = this.equModelArr.findIndex((item) => item.equModelCode === v);
      if (index !== -1) {
        return this.equModelArr[index]["modelName"];
      }
    },
    // 关联设备类型，根据父级查询子级
    queryEquipmentType() {
      this.loading = false;
      // 获取数据
      equipTypeApi.querySubAll(this.topitemtypeId).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          console.log(res);
          let data = res.data || [];
          this.equipmentTypeList = data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 获取点击的农机设备、物联设备
    topitemtype(e, equipModeData) {
      console.log("topitemtype data", e);
      this.topitemtypeId = e;
      // 获取表格数据
      this.tableData = [];
      this.equModelArr = equipModeData;
      this.equModelCode = "";
      this.queryPageList();
      let index = 0;
      let item = null;
      this.tableLabel.forEach((el, i) => {
        if (el.param === "modelName") {
          index = i;
          item = el;
          item.typeObj.list = equipModeData;
          console.log("queryAllEquModel item ", item);
        }
      });
      if (item) this.$set(this.tableLabel, index, item);
      console.log("queryAllEquModel", this.tableLabel);
      // this.queryEquipModel(e);
      //this.queryEquipmentType();
    },
    async queryPageList(e) {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...e,
          //设备类型 农机设备/物联设备
          equipmentTypeCode: this.topitemtypeId,
        },
      };
      if (this.equipmentName) {
        params.entity["equipmentName"] = this.equipmentName;
      }
      console.log("queryPageList", this.equipmentTypeCode);
      if (this.equipmentTypeCode) {
        params.entity["equipmentTypeCode"] = this.equipmentTypeCode;
      }
      if (this.equModelCode) {
        params.entity["equModelCode"] = this.equModelCode;
      }
      await equipStandingBookApi.queryPageList(params).then((res) => {
        this.loading = false;
        // 赋值总条数
        console.log(res);
        if (res.code === 1) {
          let data = res.data || {};
          this.totalSize = data.totalElements;
          data.content.forEach((item) => {
            item["operate_status"] = item.status;
          });
          // 赋值数组
          this.tableData = data.content;

          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    handleSelectionChange(list) {
      this.checkedIdList = [];
      let notvalue = true;
      let emptyList = [];
      this.checkedIdList = list.map((item) => {
        if (item.equipmentCode) {
          return item.equipmentCode;
        } else {
          notvalue = false;
          emptyList.push(item);
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        this.toggleNoSelection(emptyList);
        return;
      }
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 单个删除
    delOne(data) {
      if (!row || !row.equipmentCode) {
        return;
      }
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          var form = new FormData();
          form.append("equipmentCodeList", data.equipmentCode);
          equipStandingBookApi.delList(form).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    delmessage() {
      var form = new FormData();
      this.checkedIdList.forEach((a) => {
        form.append("equipmentCodeList", a);
      });
      equipStandingBookApi.delList(form).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.queryPageList();
          this.resetActionBar();
        }
      });
    },
    // 添加
    add() {
      console.log("add");
      this.editObject.equipmentTypeCode = this.topitemtypeId;
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      this.editActive = false;
      this.showAddEditDialog = true;
    },
    // 修改
    edit(row) {
      if (row.equipmentCode) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true;
      } else {
        this.editObject = {};
      }
    },
    completeInfo(row) {
      if (row.equipmentCode) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.showCompleteInfoDialog = true;
      }
    },
    showCompleteInfo(row) {
      if (row.equipmentCode) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.showQuipmentDetailDialog = true;
      }
    },
    // table点击事件 在配置文件中 methods 传入事件
    clickButton(val) {
      console.log("表单事件", val);

      if (val.methods === "edit") {
        this.edit(val.row);
      } else if (val.methods === "detail") {
        this.completeInfo(val.row);
      }
    },
    // 启用
    start(data) {
      this.$confirm("确认启用该设备?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          var form = {
            status: "ENABLE",
            equModelCode: data.equModelCode,
            equipmentCode: data.equipmentCode,
            equipmentName: data.equipmentName,
            modelName: data.modelName,
            operationMode: data.operationMode,
            repairNodeId: data.repairNodeId,
            selfDriving: data.selfDriving,
          };
          equipStandingBookApi.edit(form).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 停用
    stop(data) {
      data.status = "启用";
      this.$confirm("确认停用该设备?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          var form = {
            status: "DISABLE",
            equModelCode: data.equModelCode,
            equipmentCode: data.equipmentCode,
            equipmentName: data.equipmentName,
            modelName: data.modelName,
            operationMode: data.operationMode,
            repairNodeId: data.repairNodeId,
            selfDriving: data.selfDriving,
          };
          equipStandingBookApi.edit(form).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    closeDialog() {
      this.queryPageList();
      this.cancel();
    },
    cancel() {
      this.showAddEditDialog = false;
      this.showCompleteInfoDialog = false;
      this.showQuipmentDetailDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;
      this.editActive = false;
      this.$refs.tableData.setCurrentRow();
      this.$refs.tableData.clearSelection();
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-collapse-item__header {
  height: 0px;
}
::v-deep .el-collapse-item__content {
  padding-bottom: 10px;
}

::v-deep .el-form-item__label {
  min-width: 120px !important;
  text-align: end;
}

// ::v-deep .staff-manage .common-layout {
//   margin-top: 15px;
// }

.total {
  position: absolute;
  top: 25px;
  left: 300px;
}
.content-container {
  display: flex;
  height: 100%;
  width: 100%;
  .left {
    display: flex;
    overflow-y: auto;
    flex-direction: column;
    align-items: center;
    width: 25%;
    height: 100%;
    margin: 0 20px 0 0;
    font-size: 17px;
  }
  .right {
    width: 75%;
    height: 100%;
  }
}
.tree-content {
  height: calc(100% - 80px);
  overflow-y: auto;
  overflow-x: hidden;
}
::v-deep .el-form-item.is-error {
  .el-input__inner {
    border-color: #f56c6c !important;
  }
}
</style>
